﻿using System;
using System.Collections.Generic;
using System.Linq;
using EPiServer.Cms.Shell.Extensions;
using EPiServer.Core;
using EPiServer.Framework.Localization;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Shell.ObjectEditing.EditorDescriptors;

namespace OpenWaves.EPiServer.ImageProperty
{
    /// <summary>
    /// Register an editor for StringList properties
    /// </summary>
    [EditorDescriptorRegistration(TargetType = typeof(global::EPiServer.Url), UIHint = ImageProperty.UIHint)]
    [EditorDescriptorRegistration(TargetType = typeof(ContentReference), UIHint = ImageProperty.UIHint)]
    public class PropertyImageEditorDescriptor : EditorDescriptor
    {
        public PropertyImageEditorDescriptor()
        {
            this.ClientEditingClass = "ow-epi-imageProperty.widgets.ImageSelector";
        }

        public override void ModifyMetadata(ExtendedMetadata metadata,
                                            IEnumerable<Attribute> attributes)
        {
            base.ModifyMetadata(metadata, attributes);
            ExtendedMetadata mostContentMetadata = ExtendedMetadataExtensions.FindTopMostContentMetadata(metadata);
            IContent content = mostContentMetadata.Model as IContent;
            if (content == null)
                return;
            metadata.EditorConfiguration.Add("contentTypeId", (object)content.ContentTypeID);
            if (content.ContentLink != (ContentReference)null)
                metadata.EditorConfiguration.Add("contentLink", (object)content.ContentLink);
            IResourceable resourceable = content as IResourceable;
            if (resourceable == null)
                return;
            metadata.EditorConfiguration.Add("parentLink", (object)content.ParentLink);
            metadata.EditorConfiguration.Add("resourceFolderId", (object)resourceable.ContentAssetsID);
            mostContentMetadata.AdditionalValues["ResourceFolderId"] = (object)resourceable.ContentAssetsID;

            metadata.AdditionalValues["DropTargetType"] = new string[] { "fileurl" };

            // Image file extensions are from EPiServer.UI.Edit.FileManagerBrowser
            metadata.EditorConfiguration.Add("SupportedExtensions", ImageSettingsAttribute.ImageExtensions);

            metadata.OverlayConfiguration.Add("customType", "ow-epi-imageProperty.widgets.ImageOverlayType");

            metadata.EditorConfiguration.Add("clearText", LocalizationService.Current.GetString("/imageProperty/clearText", "Clear"));
            metadata.EditorConfiguration.Add("browseHtml", LocalizationService.Current.GetString("/imageProperty/browseHtml", "&lt;span class=&quot;epi-visibleLink&quot; &gt;Browse&lt;/span&gt; or drop image here"));
            metadata.EditorConfiguration.Add("supportedFormatsText", LocalizationService.Current.GetString("/imageProperty/supportedFormatsText", "Supported image formats: jpg, jpeg, jpe, ico, gif, bmp, png"));

            // custom width and height
            var settingsAttribute = attributes.OfType<ImageSettingsAttribute>().SingleOrDefault();


            var list = new List<string>();
            if (settingsAttribute != null && settingsAttribute.SupportedMediaTypes != null)
            {
                list = settingsAttribute.SupportedMediaTypes.Select(t => t.FullName.ToLowerInvariant()).ToList();
            }
            
            if(list.Any() == false)
            {
                list = ServiceLocator.Resolve<IImageMediaTypeResolver>().GetImageMediaTypes().Select(t => t.FullName.ToLowerInvariant()).ToList();
            }

            if (list.Any())
            {
                metadata.EditorConfiguration.Add("SupportedMediaTypes", (object)list);
                metadata.OverlayConfiguration.Add("SupportedMediaTypes", (object)list);
            }

            if (settingsAttribute == null || settingsAttribute.Width < 0 || settingsAttribute.Height < 0)
            {
                settingsAttribute = new ImageSettingsAttribute(100, 100);
            }

            metadata.EditorConfiguration.Add("ImageSize", new { settingsAttribute.Width, settingsAttribute.Height });
        }
    }
}